package com.example.module_motorcircle.post.adapter

import android.graphics.Color
import android.text.SpannableStringBuilder
import android.text.TextPaint
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.util.Log
import android.view.View
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.example.lib_common.utils.ToastUtils
import com.example.lib_net.model.api.PostItem
import com.example.module_motorcircle.R
import com.example.module_motorcircle.databinding.LayoutPostItemBinding

/**
 * @author yaotianxue
 * @description
 * @date 2025/2/11
 */
class PostViewHolder(
    val binding:LayoutPostItemBinding,
    private val onItemClick:((PostItem,Int)->Unit)? = null,
    private val onLikeClick:((PostItem,Int)->Unit)? = null,
    private val onCollectionClick:((PostItem,Int)->Unit)? = null,
    private val onFollowClick:((PostItem,Int)->Unit)? = null,
    private val onMoreClick:((PostItem,Int)->Unit)? = null,
    private val onCommentClick:((PostItem,Int)->Unit)? = null,
):RecyclerView.ViewHolder(binding.root) {

    fun initView(postItem:PostItem,position:Int){
        //处理话题
        binding.tvPostContent.setEllipsizeText("...")
        binding.tvPostContent.maxLines = 4
        if(postItem.topics.isNullOrEmpty()){ //无话题
            binding.tvPostContent.text = postItem.content
        }else{//有话题，富文本处理
            handleTopic(postItem,position)
        }
        //处理九宫格
        handlePicOrVideo(postItem,position)
    }

    private fun handleTopic(postItem:PostItem,position:Int){
        val content = postItem.content
        val spannableStringBuilder = SpannableStringBuilder(content)
        //保存话题的起始位置
        val topicIndexMap = mutableMapOf<String,MutableList<Int>>() //键:话题内容 值:话题开始和结束的位置
        //保存话题的id
        val topicIdMap = mutableMapOf<String,String>()//键:话题内容 值:话题id

        val topics = postItem.topics
        topics?.forEach{
            //话题前后加#
            val topicName = String.format("#%s#",it.topicName)
            //找的内容
            var temp = content

            while (true){
               val start = temp?.indexOf(topicName)
               if(start!! > -1){ //找到了
                   if(topicIndexMap[topicName] == null){
                       topicIndexMap[topicName] = mutableListOf()
                   }
                   topicIndexMap[topicName]?.add(start)
                   topicIndexMap[topicName]?.add(start+topicName.length)
                   topicIdMap[topicName] = it.topicId
               }else{ //没找到
                   break
               }
                //继续从后面开始找
                temp = temp?.substring(start+topicName.length)
            }
        }
        Log.d("handleTopic", "内容: $content")
        Log.d("handleTopic", "起始位置: $topicIndexMap")
        Log.d("handleTopic", "id: $topicIdMap")
        //富文本
        topicIndexMap.forEach{name,list ->
            spannableStringBuilder.setSpan(object :ClickableSpan(){
                override fun onClick(widget: View) {
                    ToastUtils.showLong(itemView.context,"点击了话题id ${topicIdMap[name]}")
                }

                override fun updateDrawState(ds: TextPaint) {
                    ds.color = ContextCompat.getColor(itemView.context, R.color.topic)
                    ds.isUnderlineText = false
                }

            },list[0],list[1],SpannableStringBuilder.SPAN_EXCLUSIVE_INCLUSIVE)
        }
        binding.tvPostContent.movementMethod = LinkMovementMethod.getInstance()
        binding.tvPostContent.highlightColor = Color.TRANSPARENT
        binding.tvPostContent.text = spannableStringBuilder


    }

    private fun handlePicOrVideo(postItem:PostItem,position:Int) {
        if(postItem.img != null){
            binding.nineGridView.setPicsList(postItem.img!!) //设置图片资源
        }
        binding.nineGridView.initView()
    }

    fun clickItem(){
        onItemClick?.invoke(binding.post!!,adapterPosition)
    }
    fun clickLike(){
        onLikeClick?.invoke(binding.post!!,adapterPosition)
    }
    fun clickCollection(){
        onCollectionClick?.invoke(binding.post!!,adapterPosition)
    }
    fun clickFollow(){
        onFollowClick?.invoke(binding.post!!,adapterPosition)
    }
    fun clickMore(){
        onMoreClick?.invoke(binding.post!!,adapterPosition)
    }
    fun clickComment(){
        onCommentClick?.invoke(binding.post!!,adapterPosition)
    }
}
